import {
  ApiRootUrl,
  apiList
} from '../../../config/index.js'
import Dialog from '../../../@vant/weapp/dialog/dialog';
import {
  IMG_PATH
} from '../../../config/index.js'
import {
  request,judgeData,formatDateTime,formatStringTime
} from "../../../utils/util.js"
import Toast from '../../../@vant/weapp/toast/toast';
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    IMG_PATH: IMG_PATH,
    tongzhiShow: false,
    allpendingcheckeƒd: false,
    allchecked: false,
    canTap: false,
    height: 0,
    lizhiTime:"",
    birthday:"",
    tongzhimessage: '',
    passList: [],
    minDate: new Date(2020, 0, 1).getTime(),
    maxDate: new Date().getTime(),
    currentDate: new Date().getTime(),
    // lizhiminDate: new Date(2010, 1, 1).getTime(),
    lizhimaxDate: new Date().getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}`;
      } else if (type === 'month') {
        return `${value}`;
      }
      return value;
    },
    sourceShow: false,
    dangerShow: false,
    timeshow: false,
    statusBarHeight: '',
    active: 0,
    searchValue: '',
    lizhiTimeShow: false,
    sourceName: '劳务公司',
    time: '选择时间',
    danger: '备案登记',
    isRange:false,
    dangerId:"",
    leaveTimeStart: "",
    leaveTimeEnd: "",
    sourceShowColumns: [],
    dangerShowColumns: [
      {
        id: '',
        text: '全部'
      },{
        id: '0',
        text: '未提交'
      }, {
        id: '1',
        text: '已提交'
      }, {
        id: '2',
        text: '备案中'
      }, {
        id: '3',
        text: '已备案'
      }],
    tabList: [{
      title: '待面试',
    }, {
      title: '通过',
    }, {
      title: '待定',
    }]
  },
  companyClick() {
    this.setData({
      sourceShow: true
    })
  },
  dangerShowClose() {
    this.setData({
      dangerShow: false
    })
  },
  dangerClick() {
    this.setData({
      dangerShow: true
    })
  },
  sourceShowClose() {
    this.setData({
      sourceShow: false
    })
  },
  dangerShowConfirm(event) {
    this.setData({
      danger: event.detail.value.text,
      dangerId: event.detail.value.id,
      dangerShow: false
    },()=>{
      this.getInterview()
    })
  },
  lizhiTimeClose() {
    this.setData({
      lizhiTimeShow: false
    })
  },
  familybirthdayConfirm(event) {
    console.log(event);
    let birthday = this.data.birthday;
    console.log(birthday)
    this.setData({
      lizhiTime: birthday,
      lizhiTimeShow: false,
      tongzhiShow: true
    })
  },
  lizhiTimeClick() {
    this.setData({
      lizhiTimeShow: true,
    })
  },
  birthdadInput(event) {
    let time = this.formatDate(event.detail);
    console.log(time);
    this.setData({
      birthday: time,
    });
  },
  timeClick() {
    this.myComponent.showPicker()
    this.setData({
      timeshow: true
    })
  },
  sourceShowConfirm(event) {
    let text = event.detail.value.text;
    if(text == "全部"){
      text = "劳务公司"
    }
    this.setData({
      sourceName: text,
      orgCode:event.detail.value.id,
      sourceShow: false
    },()=>{
      this.getInterview()
    })
  },
  getSearchValue(e) {
    let value = e.detail;
    this.setData({
      searchValue: value
    }, () => {
      this.getInterview()
    })
  },
  tabClick(event) {
    this.setData({
      active: event.detail.index
    })
  },
  backClick(event) {
    wx.navigateBack();
    // console.log(event);
    // Dialog.confirm({
    //   title: '返回',
    //   message: '请确认是否返回？',
    // }).then(() => {
    //   wx.navigateBack();
    // }).catch(() => {
    //   console.log('取消')
    // });
  },
  formatDate(date) {
    var date = new Date(date);
    var YY = date.getFullYear() + '-';
    var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
    return YY + MM + DD;
  },
  formateTime(time){
    let arr = time.split("-")
    return arr[0]+arr[1]+arr[2]+""
  },
  getPostId(arr) {
    let arr1 = []
    for (let i = 0; i < arr.length; i++) {
      if (arr[i].checked) {
        arr1.push(arr[i].id)
      }
    }
    return arr1
  },
  formatTime(time) {
    return time.split("-")[0] + time.split("-")[1] + time.split("-")[2]
  },
  sendClick(){
    let arr = this.getPostId(this.data.passList)
    if(arr.length == 0){
      Toast("必须选中最少一个")
      return
    }
    if(this.data.lizhiTime == ""){
      Toast("时间不能为空")
      return
    }
    let time = this.formatTime(this.data.lizhiTime)
    this.entryJob(arr,time)
  },
  selectStart(e){
    let time = this.formateTime(e.detail)
    console.log("开始时间",e)
    this.setData({
      time: `${e.detail} - ${this.data.leaveTimeEnd}`,
      leaveTimeStart:time
    })
  },
  selectEnd(e){
    let time = this.formateTime(e.detail)
    console.log("结束时间",e)
    this.setData({
      time: `${this.data.leaveTimeStart} - ${e.detail}`,
      leaveTimeEnd:time
    })
  },
  timeConfirm(event) {
    let beginTime = this.data.leaveTimeStart
    let endTime = this.data.leaveTimeEnd
    let time = beginTime+"-"+endTime
    if(!this.data.isRange){
      beginTime = "";
      endTime = "";
      time="选择时间"
    }
    this.setData({
      timeshow: false,
      leaveTimeStart:beginTime,
      leaveTimeEnd:endTime,
      time:time,
      isRange:false
    },()=>{
      this.getInterview()
    });
    this.myComponent.hidePicker()
  },
  getInterview() {
    let params = {
      // labourName: this.data.sourceName == "劳务公司" ? "":this.data.sourceName,
      labourCode:this.data.orgCode,
      name: this.data.searchValue,
      phone: "",
      beginTime:this.data.leaveTimeStart,
      endTime:this.data.leaveTimeEnd,
      surveyStatus: this.data.dangerId == "" ? "" : Number(this.data.dangerId),
      jobStatus: 0,
      flag:2
    }
    Toast.loading({
      message: '加载中...',
      mask: true,
      duration: 0,
      forbidClick: true,
    });
    request(apiList.waitInterview, params).then((res) => {
      let arr = []
      for (let i = 0; i < res.data.length; i++) {
        res.data[i].checked = false
        arr.push(res.data[i])
      }
      this.setData({
        passList: arr
      })

      Toast.clear();
    }).catch((err) => {
      Toast.clear();
      Toast({
        duration: 3000,
        forbidClick: true,
        type: 'fail',
        message: err.message,
      });
    })
  },
  entryJob(ids,time){
    let params = {
      idList:ids,
      jobTime:time,
    }
    Toast.loading({
      message: '处理中...',
      mask: true,
      duration: 0,
      forbidClick: true,
    });
    request(apiList.jobRegister,params).then((res) => {
     console.log("请求结果=====>",res)
      wx.showToast({
        title: '登记成功！',
      })
      this.setData({
        tongzhiShow:false
      })
      this.getInterview()
      Toast.clear();
    }).catch((err) => {
      this.setData({
        tongzhiShow:false
      })
      Toast.clear();
      Toast({
        duration: 3000,
        forbidClick: true,
        type: 'fail',
        message: err.message,
      });
    })
  },
  refendClick(event) {
    console.log(event);
    this.setData({
      tongzhiShow: true
    })
  },
  refendallClick(e){
    let type = Number(e.currentTarget.dataset.type)
    if(type == 0){
      this.setData({
        tongzhiShow:true
      })
    }else if(type == 1){
      let ids = []
      for(let i=0;i<this.data.passList.length;i++){
        if(this.data.passList[i].checked){
          let obj = {
            id:this.data.passList[i].id,
            openId:this.data.passList[i].openId,
            componentCode:this.data.passList[i].componentCode,
            surveyStatus:"1",
          }
          ids.push(obj)
        }
      }
      this.checkLabal(ids)
    } 
  },
  checkLabal(ids){
    let params = {
      ids:ids,
      flag:"1",
    }
    Toast.loading({
      message: '处理中...',
      mask: true,
      duration: 0,
      forbidClick: true,
    });
    request(apiList.checkLabor,params).then((res) => {
      console.log("请求结果=====>",res)
      Toast.clear();
      wx.showToast({
        title: '审核成功',
      })
      this.getInterview()
    }).catch((err) => {
      console.log("err==>",err)
      Toast.clear();
      Toast({
        duration: 3000,
        forbidClick: true,
        type: 'fail',
        message: err.message,
      });
    })
  },
  refendpendingClick(event) {
    console.log(event);
  },
  pendingChange(event) {
    let id = event.target.dataset.id;
    let dataList = this.data.determineList;
    dataList.forEach((item) => {
      if (item.id == id) {
        item.checked = event.detail
      }
    })
    this.setData({
      determineList: dataList
    })
    if (event.detail) {
      this.setData({
        allpendingchecked: true
      })
    } else {
      let list = dataList.map(value => value['checked']);
      if (list.includes(true)) {
        this.setData({
          allpendingchecked: true
        })
      } else {
        this.setData({
          allpendingchecked: false
        })
      }
    }
  },
  pendingDetailsClick(event) {
    console.log(event);
    wx.navigateTo({
      url: `../pendingdetails/pendingdetails?id=${event.target.dataset.id}&requestType=${event.target.dataset.type}`
    })
  },
  refendpendingClick(event) {
    wx.navigateTo({
      url: `../pendingdetails/pendingdetails?id=${event.target.dataset.id}&requestType=${event.target.dataset.type}`
    })
  },
  passChange(event) {
    let id = event.target.dataset.id;
    let dataList = this.data.passList;
    dataList.forEach((item) => {
      if (item.id == id) {
        item.checked = event.detail
      }
    })
    let flag = true;
    for (let i = 0; i < dataList.length; i++) {
      if (!dataList[i].checked) {
        flag = false
      }
    }
    this.setData({
      passList: dataList,
      allchecked: flag
    })
    let list = dataList.map(value => value['checked']);
    if (list.includes(true)) {
      this.setData({
        canTap: true
      })
    } else {
      this.setData({
        canTap: false
      })
    }
  },
  detailsClick(event) {
    let id = event.target.dataset.id;
    let type = event.target.dataset.type;
    let ids = event.currentTarget.dataset.ids;
    wx.navigateTo({
      url: `../pendingdetails/pendingdetails?id=${id}&type=${true}&requestType=${type}&ids=${ids}`
    })
    console.log(event);
  },
  timeClose() {
    this.setData({
      timeshow: false,
      isRange:false
    });
    this.myComponent.hidePicker()
  },
  pendingallChange(event) {
    let dataList = this.data.determineList;
    dataList.forEach((item) => {
      item.checked = event.detail;
    })
    this.setData({
      allpendingchecked: event.detail,
      determineList: dataList
    })
  },
  passallChange(event) {
    let dataList = this.data.passList;
    dataList.forEach((item) => {
      item.checked = event.detail;
    })
    this.setData({
      allchecked: event.detail,
      passList: dataList,
      canTap: event.detail
    })
  },
  tongzhiClose() {
    this.setData({
      tongzhiShow: false,
      tongzhimessage: ''
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let query = wx.createSelectorQuery();
    query.select('.content').boundingClientRect(rect => {
      let height = rect.height;
      this.setData({
        statusBarHeight: wx.getSystemInfoSync()['statusBarHeight'],
        height: wx.getSystemInfoSync().windowHeight - height,
        sourceShowColumns: app.globalData.companyList||[]
      })
    }).exec();
    this.myComponent = this.selectComponent('#timeRangeComponent')
    this.getInterview()
  },
  defalut() {
    //触发简历初始化，去除默认选择项
    const child = this.selectComponent('#Calendar');
    const child1 = this.selectComponent('#Calendar1');
    child.resetToday()
    child1.resetToday()
  },
  getRangeTime(e){
    let beginTime = formatDateTime(e.detail.begin);
    let endTime =formatDateTime(e.detail.end);
    console.log(beginTime,endTime)
    this.setData({
      leaveTimeStart:formatStringTime(beginTime),
      leaveTimeEnd:formatStringTime(endTime),
      isRange:true
    })
  },
  timeAll() {
    this.defalut()
    this.setData({
      timeshow: false,
      leaveTimeStart: "",
      leaveTimeEnd: "",
      time: "选择时间"
    }, () => {
      this.getInterview();
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})